package com.bizdk.generator.core.query;

import cn.hutool.core.util.StrUtil;
import com.bizdk.generator.core.DbType;

import java.util.StringJoiner;

/**
 * 达梦8 查询
 */
public class DmQuery implements DialectQuery {
    
    @Override
    public DbType dbType() {
        return DbType.MySQL;
    }
    
    @Override
    public String tableSql(String tableName) {
        StringBuilder sql = new StringBuilder();
        sql.append(
                "SELECT T.* FROM (SELECT DISTINCT T1.TABLE_NAME AS TABLE_NAME,T2.COMMENTS AS TABLE_COMMENT FROM USER_TAB_COLUMNS T1 ");
        sql.append("INNER JOIN USER_TAB_COMMENTS T2 ON T1.TABLE_NAME = T2.TABLE_NAME) T WHERE 1=1 ");
        // 表名查询
        if (StrUtil.isNotBlank(tableName)) {
            sql.append("and T.TABLE_NAME = '").append(tableName).append("' ");
        }
        sql.append("order by T.TABLE_NAME asc");
        
        return sql.toString();
    }
    
    
    @Override
    public String columnSql() {
        StringJoiner sql = new StringJoiner(" \n");
        sql.add("SELECT ").add("     T2.COLUMN_NAME,").add("     T1.COMMENTS,")
                .add("     CASE WHEN T2.DATA_TYPE='NUMBER' THEN (CASE WHEN T2.DATA_PRECISION IS NULL THEN T2.DATA_TYPE WHEN NVL(T2.DATA_SCALE, 0) > 0 THEN T2.DATA_TYPE||'('||T2.DATA_PRECISION||','||T2.DATA_SCALE||')' ELSE T2.DATA_TYPE||'('||T2.DATA_PRECISION||')' END) ELSE T2.DATA_TYPE END DATA_TYPE,")
                .add("     CASE WHEN CONSTRAINT_TYPE='P' THEN 'PRI' END AS KEY").add("FROM USER_COL_COMMENTS T1, ")
                .add("     USER_TAB_COLUMNS T2, ").add("     (").add("         SELECT")
                .add("             T4.TABLE_NAME,").add("             T4.COLUMN_NAME,")
                .add("             T5.CONSTRAINT_TYPE").add("         FROM USER_CONS_COLUMNS T4,")
                .add("              USER_CONSTRAINTS T5").add("         WHERE 1=1")
                .add("         AND T4.CONSTRAINT_NAME = T5.CONSTRAINT_NAME")
                .add("         AND T5.CONSTRAINT_TYPE = 'P'").add("     )T3 ").add("WHERE 1=1")
                .add("AND T1.TABLE_NAME = T2.TABLE_NAME").add("AND T1.COLUMN_NAME=T2.COLUMN_NAME")
                .add("AND T1.TABLE_NAME = T3.TABLE_NAME(+)").add("AND T1.COLUMN_NAME=T3.COLUMN_NAME(+)")
                .add("AND T1.TABLE_NAME = '%s'").add("ORDER BY T2.TABLE_NAME,T2.COLUMN_ID ").add("");
        
        return sql.toString();
    }
    
    @Override
    public String tableName() {
        return "TABLE_NAME";
    }
    
    @Override
    public String tableComment() {
        return "TABLE_COMMENT";
    }
    
    @Override
    public String columnName() {
        return "COLUMN_NAME";
    }
    
    @Override
    public String columnType() {
        return "DATA_TYPE";
    }
    
    @Override
    public String columnComment() {
        return "COMMENTS";
    }
    
    @Override
    public String columnKey() {
        return "KEY";
    }
}
